package team.archai.nexus.boot.web.providers;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import team.archai.nexus.boot.auth.entity.JwtParam;
import team.archai.nexus.boot.auth.entity.JwtUser;
import team.archai.nexus.boot.auth.exception.UserNotFountException;
import team.archai.nexus.boot.auth.model.AuthRequest;
import team.archai.nexus.boot.auth.token.IAuth;
import team.archai.nexus.boot.auth.util.AuthUtil;
import team.archai.nexus.boot.tool.Tool;
import team.archai.nexus.boot.web.service.AuthService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 自定义登陆验证
 * @author: lishibin
 * @create: 2020-07-11 11:48
 **/
@Component
@ConditionalOnProperty(name = "archai-nexus.auth.type", havingValue = "security")
public class AuthProvider implements AuthenticationProvider {

    @Resource
    private AuthService<JwtUser> authService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Object authDetail = authentication.getDetails();
        // 获取表单输入中返回的用户名
        String userName = Tool.toStr(authentication.getPrincipal());
        // 获取表单中输入的密码
        String password = Tool.toStr(authentication.getCredentials());
        if (null != authDetail) {
            AuthRequest authRequest = (AuthRequest) authDetail;
            password = "";
            userName = "";
        }
        JwtUser jwtUser = authService.loadUserByNameAndPassword(userName, password);
        if (null == jwtUser) {
            throw new UserNotFountException("user is not existed");
        }
        JwtParam jwtParam = JwtParam.builder().build();
        jwtParam.setCredential(jwtUser.getPassword());
        jwtParam.setSubject(jwtUser.getUserName());
        IAuth iAuth = AuthUtil.initAuth(jwtParam);
        List<GrantedAuthority> authorities = new ArrayList<>();
                //authService.permissions(jwtUser.getUserId());
        return new UsernamePasswordAuthenticationToken(iAuth.getPrincipal(), iAuth.getCredentials(), authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
